import { Card, Button, Form, Switch, Input, message, Alert, Slider } from 'antd';
import { motion } from 'framer-motion';
import { Settings, Database, Save, RotateCcw, FolderOpen } from 'lucide-react';
import { useState, useEffect } from 'react';
import { invoke } from '@tauri-apps/api/tauri';
import { open } from '@tauri-apps/api/dialog';

const SettingsPage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [autoBackupEnabled, setAutoBackupEnabled] = useState(false);
  const [backupRetention, setBackupRetention] = useState(7);
  const [backupPath, setBackupPath] = useState('C:\\Backups');

  // 加载设置
  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    try {
      // 从后端加载设置
      const autoBackup = await invoke('get_setting', { key: 'auto_backup' });
      const backupPath = await invoke('get_setting', { key: 'backup_path' });
      const backupRetention = await invoke('get_setting', { key: 'backup_retention' });
      
      const retentionValue = backupRetention ? parseInt(backupRetention as string) || 7 : 7;
      const pathValue = (backupPath as string) || 'C:\\Backups';
      
      form.setFieldsValue({
        autoBackup: autoBackup === 'true',
        backupPath: pathValue,
        backupRetention: retentionValue
      });
      
      setAutoBackupEnabled(autoBackup === 'true');
      setBackupRetention(retentionValue);
      setBackupPath(pathValue);
    } catch (error) {
      console.error('加载设置失败:', error);
      message.error('加载设置失败');
    }
  };

  const handleSaveSettings = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      // 保存到后端
      await invoke('set_setting', { key: 'auto_backup', value: values.autoBackup ? 'true' : 'false' });
      await invoke('set_setting', { key: 'backup_path', value: values.backupPath });
      await invoke('set_setting', { key: 'backup_retention', value: values.backupRetention.toString() });
      
      setAutoBackupEnabled(values.autoBackup);
      setBackupRetention(values.backupRetention);
      setBackupPath(values.backupPath);
      message.success('设置保存成功');
    } catch (error) {
      console.error('保存设置失败:', error);
      message.error('保存设置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleResetSettings = async () => {
    try {
      setLoading(true);
      
      // 重置为默认值
      await invoke('set_setting', { key: 'auto_backup', value: 'false' });
      await invoke('set_setting', { key: 'backup_path', value: 'C:\\Backups' });
      await invoke('set_setting', { key: 'backup_retention', value: '7' });
      
      form.setFieldsValue({
        autoBackup: false,
        backupPath: 'C:\\Backups',
        backupRetention: 7
      });
      
      setAutoBackupEnabled(false);
      setBackupRetention(7);
      setBackupPath('C:\\Backups');
      message.success('设置已重置为默认值');
    } catch (error) {
      console.error('重置设置失败:', error);
      message.error('重置设置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSelectBackupPath = async () => {
    try {
      const selected = await open({
        directory: true,
        multiple: false,
        title: '选择备份目录'
      });
      
      if (selected && typeof selected === 'string') {
        form.setFieldValue('backupPath', selected);
        setBackupPath(selected);
      }
    } catch (error) {
      console.error('选择目录失败:', error);
      message.error('选择目录失败');
    }
  };

  return (
    <motion.div 
      initial={{ opacity: 0, y: 20 }} 
      animate={{ opacity: 1, y: 0 }} 
      transition={{ duration: 0.6 }}
      className="space-y-6"
    >
      <div className="card-container">
        <Card className="card">

          <div className="max-w-2xl mx-auto">
            <Card 
              title={
                <div className="flex items-center space-x-2">
                  <Database size={20} className="text-accent-500" />
                  <span>自动备份设置</span>
                </div>
              }
              className="card "
              style={{ background: '#262626' }}
            >
              <Form 
                form={form} 
                layout="vertical" 
                className="space-y-6"
              >
                <Form.Item 
                  label="启用自动备份" 
                  name="autoBackup" 
                  valuePropName="checked"
                >
                  <Switch 
                    className="bg-gray-600"
                    onChange={(checked) => setAutoBackupEnabled(checked)}
                  />
                </Form.Item>

                {autoBackupEnabled && (
                  <Alert
                    message="自动备份已启用"
                    description="系统将自动备份数据库文件，确保数据安全"
                    type="info"
                    showIcon
                    icon={<Database size={16} />}
                    className="mb-4"
                  />
                )}

                <Form.Item 
                  label="备份路径" 
                  name="backupPath"
                  rules={[{ required: true, message: '请输入备份路径' }]}
                >
                  <Input.Group compact>
                    <Input 
                      placeholder="C:\Backups"
                      style={{ width: 'calc(100% - 70px)' }}
                      className="bg-dark-secondary border-dark-border text-text-primary"
                      disabled={!autoBackupEnabled}
                      value={backupPath}
                      onChange={(e) => {
                        setBackupPath(e.target.value);
                        form.setFieldValue('backupPath', e.target.value);
                      }}
                    />
                    <Button 
                      className="btn-secondary" 
                      onClick={handleSelectBackupPath}
                      disabled={!autoBackupEnabled}
                      style={{ 
                        width: '60px',
                        height: '40px',
                        marginLeft: '8px'
                      }}
                    >
                      浏览
                    </Button>
                  </Input.Group>
                </Form.Item>

                <Form.Item 
                  label="保留备份数量" 
                  name="backupRetention"
                  rules={[
                    { required: true, message: '请输入保留数量' },
                    { type: 'number', min: 1, max: 100, message: '保留数量必须在 1-100 之间' }
                  ]}
                >
                  <div className="space-y-4">
                    <Slider 
                      min={1}
                      max={100}
                      step={1}
                      value={backupRetention}
                      disabled={!autoBackupEnabled}
                      onChange={(value) => {
                        setBackupRetention(value);
                        form.setFieldValue('backupRetention', value);
                      }}
                      className="mb-2"
                    />
                    <Input 
                      type="number"
                      min={1}
                      max={100}
                      value={backupRetention}
                      placeholder="7"
                      className="bg-dark-secondary border-dark-border text-text-primary w-24"
                      disabled={!autoBackupEnabled}
                      onChange={(e) => {
                        const value = parseInt(e.target.value);
                        if (value >= 1 && value <= 100) {
                          setBackupRetention(value);
                          form.setFieldValue('backupRetention', value);
                        }
                      }}
                    />
                  </div>
                </Form.Item>

                <div className="bg-dark-secondary p-4 rounded-lg">
                  <h4 className="text-text-primary font-medium mb-2">备份说明</h4>
                  <ul className="text-text-secondary text-sm space-y-1">
                    <li>• 自动备份将在每次重启后执行</li>
                    <li>• 备份文件将保存在指定的备份路径中</li>
                    <li>• 超过保留数量的旧备份文件将被自动删除</li>
                    <li>• 备份文件包含完整的数据库</li>
                  </ul>
                </div>
              </Form>
            </Card>

            <div className="flex justify-center space-x-4 mt-8">
              <Button 
                type="primary" 
                size="large" 
                className="btn-primary"
                icon={<Save size={16} />}
                onClick={handleSaveSettings}
                loading={loading}
              >
                保存设置
              </Button>
              <Button 
                size="large" 
                className="btn-secondary"
                icon={<RotateCcw size={16} />}
                onClick={handleResetSettings}
                loading={loading}
              >
                重置默认
              </Button>
            </div>
          </div>
        </Card>
      </div>
    </motion.div>
  );
};

export default SettingsPage; 